import { allAsyncRoutes } from "./../router/routes";
import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import { staticRoutes, anyRoute } from "@/router/routes";
import { loginApi, logoutApi, infoApi } from "@/api/acl/login";
import type { RouteRecordRaw } from "vue-router";
import router from "@/router";
// 过滤保留拥有访问权限路由菜单
const filterAsyncRouters = (
  asyncRoutes: Array<RouteRecordRaw>,
  routes: string[]
) => {
  return asyncRoutes.filter((route) => {
    // 判断遍历的每个路由的name在不在routes中
    if (routes.includes(route.name as string)) {
      // 包含就保留
      if (route.children && route.children.length) {
        // 将子菜单也进行过滤
        route.children = filterAsyncRouters(route.children, routes);
      }
      return true;
    }
    // 不包含就过滤
    return false;
  });
};
// 动态追加路由
const addRoutes = (hasPermissionRoutes: Array<RouteRecordRaw>) => {
  hasPermissionRoutes.forEach((route) => {
    // 动态添加路由
    router.addRoute(route);
  });
};

const addComponent = (routes: any) => {
  routes.forEach((route: any) => {
    route.component = () => import(route.component);
    if (route.children && route.children.length) {
      addComponent(route.children);
    }
  });
};
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: "",
    avatar: "",
    menuRoutes: [],
    buttons: [],
    routes: [],
  }),

  actions: {
    async login(username: string, password: string) {
      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     if (username==='admin' && password==='111111') {
      //       const token = 'token-atguigu'
      //       setToken(token)
      //       this.token = token
      //       resolve(token)
      //     } else {
      //       reject(new Error('用户名或密码错误!'))
      //       ElMessage.error('用户名或密码错误!')
      //     }
      //   }, 1000)
      // })
      const { token } = await loginApi(username, password);
      this.token = token;
      setToken(token);
    },
    async logout() {
      await logoutApi();
      this.reset(); // 推出后清除本地数据
    },
    async getInfo() {
      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     this.name = "admin";
      //     this.avatar =
      //       "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
      //     this.menuRoutes = staticRoutes;
      //     resolve({ name: this.name, avatar: this.avatar, token: this.token });
      //   }, 1000);
      // });
      const res = await infoApi();
      this.name = res.name;
      this.avatar = res.avatar;
      this.buttons = res.buttons; // 按钮权限
      this.routes = res.routes; // 路v由权限
      // this.menuRoutes = staticRoutes; // 左侧菜单
      const hasPermissionRoutes = filterAsyncRouters(
        allAsyncRoutes,
        res.routes
      );
      // 动态添加路由
      addRoutes([...hasPermissionRoutes, anyRoute]);
      this.menuRoutes = [...staticRoutes, ...hasPermissionRoutes]; // 左侧菜单
    },

    reset() {
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.name = "";
      this.avatar = "";
    },
  },
});
